<?php
/**
 * 消息模板模型
 * 作者: 王勇程 (laughskydragon@qq.com)
 */

namespace app\common\model;

use app\common\model\ModelBase;

class MessageTemplate extends ModelBase
{
    // 表名

    
    // 自动时间戳
    protected $autoWriteTimestamp = true;
    protected $createTime = 'create_time';
    protected $updateTime = 'update_time';
    
    // 字段类型转换
    protected $type = [
        'id' => 'integer',
        'type' => 'integer',
        'level' => 'integer',
        'status' => 'integer',
        'create_time' => 'integer',
        'update_time' => 'integer',
    ];
    
    /**
     * 获取变量说明解析
     */
    public function getVariablesAttr($value)
    {
        return $value ? json_decode($value, true) : [];
    }
    
    /**
     * 设置变量说明
     */
    public function setVariablesAttr($value)
    {
        return is_array($value) ? json_encode($value, JSON_UNESCAPED_UNICODE) : $value;
    }
    
    /**
     * 根据代码获取模板
     */
    public function getTemplateByCode($code)
    {
        return $this->getInfo(['code' => $code, 'status' => 1]);
    }
    
    /**
     * 渲染模板
     */
    public function renderTemplate($code, $variables = [])
    {
        $template = $this->getTemplateByCode($code);
        
        if (!$template) {
            return false;
        }
        
        $title = $template['title'];
        $content = $template['content'];
        
        // 替换变量
        foreach ($variables as $key => $value) {
            $placeholder = '{' . $key . '}';
            $title = str_replace($placeholder, $value, $title);
            $content = str_replace($placeholder, $value, $content);
        }
        
        return [
            'title' => $title,
            'content' => $content,
            'type' => $template['type'],
            'level' => $template['level']
        ];
    }
    
    /**
     * 获取模板列表
     */
    public function getTemplateList($type = null, $status = 1)
    {
        $where = ['status' => $status];
        
        if ($type !== null) {
            $where['type'] = $type;
        }
        
        return $this->getList($where, true, 'type asc, id asc', false);
    }
}